package org.massi.imslp.query;

public final class URLParamEncoder
{
	private URLParamEncoder()
	{
		// private constructor
	}


	/**
	 * Encode an input string
	 * 
	 * @param input the string to encode: may be null
	 * @return the encoded string, or null if te input string is null
	 */
	public static String encode(final String input)
	{
		if (input == null)
		{
			return null;
		}
		final StringBuilder resultStr = new StringBuilder();
		for (final char ch : input.toCharArray())
		{
			if (isUnsafe(ch))
			{
				resultStr.append('%');
				resultStr.append(toHex(ch / 16));
				resultStr.append(toHex(ch % 16));
			}
			else
			{
				resultStr.append(ch);
			}
		}
		return resultStr.toString();
	}


	/**
	 * hex representation of the char
	 * 
	 * @param ch the char
	 * @return hex representation
	 */
	private static char toHex(final int ch)
	{
		return (char)(ch < 10 ? '0' + ch : 'A' + ch - 10);
	}


	/**
	 * is the char unsafe?
	 * 
	 * @param ch the char
	 * @return <code>true</code> if the char is < 128
	 */
	private static boolean isUnsafe(final char ch)
	{
		if (ch > 128 || ch < 0)
		{
			return true;
		}
		return " %$&+,/:;=?@<>#%".indexOf(ch) >= 0;
	}

}
